var objectId;
var objectUrl;
var status;
var interval;

$(document).on('pageinit', function() {
	
	/* General buttons */
	$('.generalButton').off('vclick').on('vclick', executeAction);
	
	/* Logout button */
	$('.ui-header').off('vclick').on('vclick', '#logout', {callback:logOut}, executeAction);
	
	/* Afterwork init */
	$('#afterwork .openPopup').off('vclick').on('vclick',openPopup);
	$('#Sondage a, #afterwork .vote').off('vclick').on('vclick', confirmAfterwork);	
	
	/* Add afterwork */
	$('#addAfterwork').validate({
	    errorClass: "invalid",
		errorPlacement: function(error, element) {
			if (element.attr("name") === "description") {
				error.insertAfter(element);
			}
			else if(element.attr("name") === "date"){
				error.insertAfter(element.parent().parent());
			}
			else {
				error.insertAfter(element.parent());
			}
		}
	});
	
	/* Chat */
	$('#chatButton').off('vclick').on('vclick', loadChat);
});

/* General */
function executeAction(e){
	e.preventDefault();
	e.stopPropagation();
	var me=$(this);
	
	$.mobile.loading( 'show' );
	$.post(
		$(this).attr('href'),
		function(data){
			if (e.data != null)
			{
				e.data.callback(me);
			}
		
			if (data != "")
			{
				popupInfo(data);
			}
			$.mobile.loading( 'hide' );
		}
	);
}

/* Logout */
function logOut(e){
	$.mobile.changePage( '/', {
		type: "post",
		transition: "pop",
		reloadPage:true
	});
}

/* Popup info*/
function popupInfo(text){
	$('#popupInfo').html(text).popup('open', {transition:'pop'});
	setTimeout(function() {
		$('#popupInfo').popup('close');
	}, 2000);
}

/* Popup */
function openPopup(e){
	e.preventDefault();
	
	$('form.popupCss .ui-btn').removeClass('ui-btn-active');
	
	$($(this).attr('href')).popup("open", {tolerance:"30,15,30,15", transition:"pop"});
}

function closePopup(){	
	$('.ui-popup').popup("close");
}

/* Afterwork */
function confirmAfterwork(e){
	e.preventDefault();
	e.stopPropagation();
	
	afterId = $(this).data('afterid');
	
	$.mobile.loading( 'show' );
	$.post(
		$(this).attr('href'),
		{af_id:afterId},
		function(data){
			closePopup();
			$.mobile.loading( 'hide' );
			if (data.length > 5)
			{
				setTimeout(function() {
					popupInfo(data);
				}, 200);
			}
			else
				window.location.href ='/Afterwork/Detail/id/' + afterId;
		},
		'text'
	);
}

/* Chat */
function loadChat(e){
	e.preventDefault();
	e.stopPropagation();
	
	if(document.getElementById("chat") != null && $('#chat').css('display') != 'none')
	{
		$('#chat').hide();
		clearInterval(interval);
	}
	else
	{
		if ($('#chat').html() != null)
			$('#chat').show();
		else
			$.get(
				$(this).attr('href'),
				function(data){
					$('#page').append(data);
					$('#chat').draggable({ handle: "#handle", axis: "x" });
					$('#chat').phpfreechat({ serverUrl: '/phpfreechat-2.1.0/server' });
				}
			);
	}
}
